<script setup>
import { reactive, ref, onMounted, onBeforeMount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import { useInfoStore } from '@/stores/info'
// const infoStore = useInfoStore()
import { useCategoryHook } from '@/hook/infoHook'
import { UploadFile } from '@/api/common'
import { GetDetailed, InfoCreate, InfoEdit } from '@/api/info'

let $router = useRouter()
let $route = useRoute()

// let id = $route.params.id||sessionStorage.get("id");
// let name = $route.params.name||sessionStorage.get("name");

let { proxy } = getCurrentInstance()
let { infoData, handleGetCategory } = useCategoryHook()
const editor = ref(null)
const formRef = ref(null)
let editor_instance = null
onBeforeMount(async () => {
  // let categoryData = await infoStore.getCategory()
  // // console.log(categoryData)
  // data.category_options = categoryData
  handleGetCategory()
  data.row_id && handleGetDetailed()
})
onMounted(() => {
  editor_instance = new WangEditor(editor.value)
  Object.assign(editor_instance.config, {
    onchange(value) {
      field.content = value
      // console.log('change')
    }
  })
  editor_instance.create()
})
const data = reactive({
  cascader_props: {
    label: 'category_name',
    value: 'id'
  },
  row_id: $route.query.id
})
const field = reactive({
  status: null,
  image_url: null,
  category_id: [],
  title: null,
  create_date: null,
  content: null
  // status: '1',
  // image_url: 'http://localhost:5173/src/assets/bg.gif',
  // category_id: [2546, 2548, 2549],
  // title: 'qqq',
  // create_date: '2025-01-10T16:02:00.000Z',
  // content: '<p>aaa</p>'
})
const form_rules = {
  category_id: [{ required: true, message: '分类不能为空', trigger: 'change' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'change' }],
  image_url: [{ required: true, message: '图片不能为空', trigger: 'change' }],
  create_date: [{ required: true, message: '创建时间不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'change' }]
}
const handleOnSuccess = () => {}
const handleOnError = () => {}
const handleBeforeOnUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' // 限制上次jpg文件格式
  const isLt2M = file.size / 1024 / 1024 < 2 // 限制文件大小不能超过2MB
  if (!isJPG) {
    proxy.$message.error('上传图片格式只能是JPG格式')
    return false
  }
  if (!isLt2M) {
    proxy.$message.error('上传图片大小不能超过2MB')
    return false
  }
  return isJPG && isLt2M
}
// 自定义方法的调用
const handleUpload = async (params) => {
  // console.log(params)
  const file = params.file
  const form = new FormData()
  form.append('files', file)
  let res = await UploadFile(form)
  field.image_url = res.data.files_path
}
const handleEditInfo = async () => {
  const request_data = JSON.parse(JSON.stringify(field))
  request_data.create_date = dayjs(request_data.create_date).format('YYYY-MM-DD HH:mm:ss')
  if (typeof request_data.category_id !== 'string') {
    request_data.category_id = request_data.category_id[request_data.category_id.length - 1]
  }
  // console.log(request_data)
  try {
    let res = await InfoEdit(request_data)
    proxy.$message.success(res.message)
    $router.go(-1)
  } catch (error) {}
}
const handleAddInfo = async () => {
  const request_data = JSON.parse(JSON.stringify(field))
  request_data.create_date = dayjs(request_data.create_date).format('YYYY-MM-DD HH:mm:ss')
  request_data.category_id = request_data.category_id[request_data.category_id.length - 1]
  // console.log(request_data)
  try {
    let res = await InfoCreate(request_data)
    proxy.$message.success(res.message)
    $router.go(-1)
  } catch (error) {}
}
const handleSubmitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // console.log(field)
      data.row_id ? handleEditInfo() : handleAddInfo()
    } else {
      console.log('error sumbit')
      return false
    }
  })
}
const handleGetDetailed = async () => {
  let res = await GetDetailed({ id: data.row_id })
  // field = res.data
  Object.assign(field, res.data)
  editor_instance.txt.html(res.data.content)
}
</script>
<template>
  <el-form ref="formRef" :model="field" :rules="form_rules" label-width="150px">
    <el-form-item label="类别信息：" prop="category_id">
      <el-cascader
        v-model="field.category_id"
        :options="infoData.category_options"
        :props="data.cascader_props"
      >
      </el-cascader>
    </el-form-item>
    <el-form-item label="信息标题：" prop="title">
      <el-input v-model="field.title"></el-input>
    </el-form-item>
    <el-form-item label="缩略图：" prop="image_url">
      <el-upload
        class="avatar-uploader"
        action="#"
        :http-request="handleUpload"
        :before-upload="handleBeforeOnUpload"
        :on-success="handleOnSuccess"
        :on-error="handleOnError"
        :show-file-list="false"
      >
        <img v-if="field.image_url" :src="field.image_url" class="avatar" />
        <span v-else>+</span>
      </el-upload>
    </el-form-item>
    <el-form-item label="发布日期:" prop="create_date">
      <el-date-picker
        v-model="field.create_date"
        type="datetime"
        placeholder="选择日期时间"
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="内容:" prop="content">
      <div ref="editor"></div>
    </el-form-item>
    <el-form-item label="是否发布：" prop="status">
      <el-radio-group v-model="field.status">
        <el-radio :value="'1'">是</el-radio>
        <el-radio :value="'0'">否</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item>
      <el-button type="danger" @click="handleSubmitForm">确定</el-button>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.avatar-uploader,
.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
}
</style>
